<script>
  import FieldLabel from "./FieldLabel.svelte";
  import BaseButton from "./BaseButton.svelte";

  export let label = "";
  export let required = false;
  export let values = [""];
  export let placeholder = "";
  export let readonly = false;
  export let error = "";
  export let disabled = false;
  export let showHeader = true; // 控制是否显示header
  export let customErrorMessage = ""; // 新增：自定义校验错误提示
  export let invalidRows = []; // 新增：标记哪些行校验不通过
  export let rowMaxLength = null; // 新增：每行最大长度限制

  // 表单引用
  let fieldRef;

  function addValue() {
    values = [...values, ""];
  }

  function removeValue(index) {
    if (values.length > 1) {
      values = values.filter((_, i) => i !== index);
      // 更新无效行索引
      invalidRows = invalidRows
        .filter(i => i !== index) // 移除当前行的无效标记
        .map(i => i > index ? i - 1 : i); // 调整后续行的索引
      
      // 如果没有无效行了，清除自定义错误消息
      if (invalidRows.length === 0) {
        customErrorMessage = "";
      }
    }
  }

  // 导出方法供外部调用
  export function addRow() {
    addValue();
  }

  export function removeRow(index) {
    removeValue(index);
  }

  export function getRowCount() {
    return values.length;
  }

  export function clearAllRows() {
    values = [""];
  }

  // 验证函数 - 保持原有逻辑不变
  export function validate() {
    const validValues = values.filter((v) => v && v.trim() !== "");
    if (required && validValues.length === 0) {
      error = `请至少添加一个${label}`;
      return false;
    }
    
    // 添加行长度校验
    if (rowMaxLength) {
      for (let i = 0; i < values.length; i++) {
        if (values[i] && values[i].length > rowMaxLength) {
          error = `第${i + 1}行内容不能超过${rowMaxLength}个字符`;
          return false;
        }
      }
    }
    
    error = "";
    return true;
  }

  // 修改：自定义校验函数 - 动态更新无效行状态
  export function validateCustom(validator, errorMessage = "数据格式不正确") {
    if (!validator || typeof validator !== 'function') {
      return true;
    }

    const newInvalidRows = [];
    values.forEach((value, index) => {
      // 只对非空值进行校验
      if (value.trim() !== "" && !validator(value, index)) {
        newInvalidRows.push(index);
      }
    });

    // 更新无效行状态
    invalidRows = newInvalidRows;
    
    if (newInvalidRows.length > 0) {
      customErrorMessage = errorMessage;
      return false;
    } else {
      customErrorMessage = "";
      return true;
    }
  }

  // 新增：实时校验方法 - 在输入时动态更新行状态
  export function validateRealtime(validator) {
    if (!validator || typeof validator !== 'function') {
      invalidRows = [];
      return;
    }

    const newInvalidRows = [];
    values.forEach((value, index) => {
      // 只对非空值进行校验
      if (value.trim() !== "" && !validator(value, index)) {
        newInvalidRows.push(index);
      }
    });

    invalidRows = newInvalidRows;
  }

  // 新增：清除自定义校验错误
  export function clearCustomError() {
    customErrorMessage = "";
    invalidRows = [];
  }

  // 新增：设置自定义校验错误
  export function setCustomError(message, rowIndexes = []) {
    customErrorMessage = message;
    invalidRows = Array.isArray(rowIndexes) ? rowIndexes : [];
  }

  // 新增：检查是否有自定义校验错误
  export function hasCustomError() {
    return !!customErrorMessage || invalidRows.length > 0;
  }

  function handleInput(index) {
    // 输入时清除当前行的自定义错误状态（如果现在有效了）
    if (invalidRows.includes(index)) {
      // 可以在这里添加实时校验逻辑
      // 如果需要实时校验，可以调用一个校验函数
    }
    
    // 输入时清除必填错误
    if (error) {
      const validValues = values.filter((v) => v && v.trim() !== "");
      if (validValues.length > 0) {
        error = "";
      }
    }
    
    // 实时长度校验
    if (rowMaxLength && values[index] && values[index].length <= rowMaxLength) {
      error = "";
    }
  }

  function handleBlur() {
    // 失焦时验证
    if (required) {
      const validValues = values.filter((v) => v && v.trim() !== "");
      if (validValues.length === 0) {
        validate();
      }
    }
  }
</script>

<div class="multiple-field" bind:this={fieldRef}>
  {#if label && showHeader}
    <div class="field-header">
      <FieldLabel {label} {required} />
      {#if !readonly}
        <BaseButton text size="small" {disabled} on:click={addValue}>
          <svg
            slot="icon"
            width="16"
            height="16"
            viewBox="0 0 16 16"
            fill="currentColor"
          >
            <path
              d="M7.33398 7.83398V3.83398H8.66732V7.83398H12.6673V9.16732H8.66732V13.1673H7.33398V9.16732H3.33398V7.83398H7.33398Z"
            />
          </svg>
        </BaseButton>
      {/if}
    </div>
  {/if}

  {#if readonly}
    <div class="readonly-value">
      {values.filter((v) => v && v.trim()).join(", ") || "-"}
    </div>
  {:else}
    {#each values as value, index}
      <div class="value-item">
        <input
          type="text"
          bind:value={values[index]}
          {placeholder}
          {disabled}
          maxlength={rowMaxLength}
          class:error={!!error && !invalidRows.includes(index)}
          class:row-invalid={invalidRows.includes(index)}
          on:input={() => handleInput(index)}
          on:blur={handleBlur}
        />
        {#if values.length > 1}
          <BaseButton
            size="small"
            variant="danger"
            text
            {disabled}
            on:click={() => removeValue(index)}
          >
            <svg
              width="16"
              height="16"
              viewBox="0 0 16 16"
              slot="icon"
              fill="currentColor"
            >
              <path
                d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"
              />
            </svg>
          </BaseButton>
        {/if}
      </div>
    {/each}
  {/if}

  <!-- 优先显示必填校验错误，其次显示自定义校验错误 -->
  {#if error}
    <div class="field-error">{error}</div>
  {:else if customErrorMessage}
    <div class="field-error">{customErrorMessage}</div>
  {/if}
</div>

<style>
  .multiple-field {
    margin-bottom: 24px;
  }

  .multiple-field:last-child {
    margin-bottom: 0;
  }

  .field-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
  }

  .value-item {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    align-items: center;
  }

  .value-item input {
    flex: 1;
    padding: 8px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 13px;
    background: #fff;
    box-sizing: border-box;
    color: #333;
    transition:
      border-color 0.2s,
      box-shadow 0.2s;
  }

  .value-item input::placeholder {
    color: #ccc;
  }

  .value-item input:focus {
    outline: none;
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  }

  .value-item input:disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
  }

  .value-item input.error {
    border-color: #ff4d4f;
  }

  .value-item input.error:focus {
    border-color: #ff4d4f;
    box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.1);
  }

  .value-item input.row-invalid {
    border-color: #EE4646 !important;
    background: rgba(238, 70, 70, 0.05) !important;
  }

  .value-item input.row-invalid:focus {
    border-color: #EE4646 !important;
    box-shadow: 0px 0px 3px 0px #EE4646 !important;
  }

  .readonly-value {
    padding: 8px 0;
    font-size: 13px;
    color: #333;
    line-height: 1.5;
    word-break: break-all;
    min-height: 21px;
  }

  .field-error {
    margin-top: 4px;
    font-size: 12px;
    color: rgba(238, 70, 70, 1);
  }
</style>
